<!-- 企业认证 2025-07-29 14:00徐安修改 -->
<template>
    <view class="company-auth-bg">
      <!-- 顶部导航栏 -->
  
      <view class="company-auth-container">
        <uni-forms ref="formRef" :modelValue="form" :rules="rules" label-width="90">
          <!-- 企业名称 -->
          <uni-forms-item label="企业名称" name="name" required>
            <uni-easyinput v-model="form.name" placeholder="请输入企业名称" />
          </uni-forms-item>
          <!-- 统一社会信用代码 -->
          <uni-forms-item label="信用代码" name="creditCode" required :error-message="creditCodeError">
            <uni-easyinput v-model="form.creditCode" placeholder="请输入18位统一社会信用代码" maxlength="18" @input="onCreditCodeInput" />
          </uni-forms-item>
          <!-- 企业类型 -->
          <uni-forms-item label="企业类型" name="companyType" required>
            <picker :range="companyTypeOptions" :value="companyTypeIndex" @change="onCompanyTypeChange">
              <view class="picker-view">{{ companyTypeOptions[companyTypeIndex] || '请选择企业类型' }}</view>
            </picker>
          </uni-forms-item>
          <!-- 身份类型 -->
          <uni-forms-item label="身份类型" name="identityType" required>
            <picker :range="identityTypeOptions" :value="identityTypeIndex" @change="onIdentityTypeChange">
              <view class="picker-view">{{ identityTypeOptions[identityTypeIndex] || '请选择身份类型' }}</view>
            </picker>
          </uni-forms-item>
          <!-- 证明材料上传 -->
          <uni-forms-item label="证明材料" name="files" required>
            <uni-file-picker
              v-model="form.files"
              file-mediatype="image"
              :file-extname="['jpg','png','pdf']"
              :limit="3"
              :sizeType="['original','compressed']"
              :max-size="10 * 1024 * 1024"
              @select="onFileSelect"
              @progress="onFileProgress"
              @success="onFileSuccess"
              @fail="onFileFail"
              :auto-upload="false"
              mode="grid"
            />
            <view v-if="fileUploadError" class="error-msg">{{ fileUploadError }}</view>
          </uni-forms-item>
          <!-- 认证说明 -->
          <uni-forms-item label="认证说明" name="desc" label-position="top">
            <textarea
              v-model="form.desc"
              class="desc-textarea"
              placeholder="可选，补充说明"
              maxlength="200"
              :auto-height="true"
            />
          </uni-forms-item>
        </uni-forms>
        <button class="submit-btn" type="primary" @click="onSubmit" :loading="submitting">提交认证</button>
      </view>
    </view>
  </template>
  
  <script setup>
  import { ref, reactive, computed, watch } from 'vue'
  import { onLoad, onShow } from '@dcloudio/uni-app'
  import { NETWORK_CONFIG } from '@/config/network.js'
  
  // 企业类型选项
  const companyTypeOptions = ['学校', '政府机构', '民营企业', '国有企业', '其他']
  const identityTypeMap = {
    '学校': ['学生', '教师', '行政人员', '其他'],
    '政府机构': ['员工', '管理层', '创始人', '其他'],
    '民营企业': ['员工', '管理层', '创始人', '其他'],
    '国有企业': ['员工', '管理层', '创始人', '其他'],
    '其他': ['员工', '管理层', '创始人', '其他']
  }
  
  // 表单数据
  const form = reactive({
    name: '',
    creditCode: '',
    companyType: '',
    identityType: '',
    files: [], // uni-file-picker v-model
    desc: ''
  })
  
  const companyTypeIndex = ref(-1)
  const identityTypeIndex = ref(-1)
  const identityTypeOptions = ref([])
  
  // 校验规则
  const rules = {
    name: {
      required: true, errorMessage: '企业名称不能为空'
    },
    creditCode: {
      required: true, errorMessage: '信用代码不能为空',
      validateFunction: (rule, value) => {
        if (!/^([0-9A-Z]{18})$/.test(value)) {
          return '统一社会信用代码格式错误'
        }
        return true
      }
    },
    companyType: {
      required: true, errorMessage: '请选择企业类型'
    },
    identityType: {
      required: true, errorMessage: '请选择身份类型'
    },
    files: {
      required: true, errorMessage: '请上传证明材料'
    }
  }
  
  // 实时校验信用代码
  const creditCodeError = ref('')
  function onCreditCodeInput(val) {
    form.creditCode = val.toUpperCase()
    if (val && !/^([0-9A-Z]{0,18})$/.test(val)) {
      creditCodeError.value = '仅支持大写字母和数字'
    } else if (val.length === 18 && !/^([0-9A-Z]{18})$/.test(val)) {
      creditCodeError.value = '统一社会信用代码格式错误'
    } else {
      creditCodeError.value = ''
      // 长度为18且格式正确时，尝试从后端查询企业信息并自动回填
      if (val.length === 18) {
        fetchOrgByCreditCode(val.toUpperCase())
      }
    }
  }

  // 根据信用代码查询企业信息并回填
  async function fetchOrgByCreditCode(code) {
    try {
      const [err, res] = await uni.request({
        url: `${NETWORK_CONFIG.API_BASE_URL}/organizations/by-credit?creditCode=${code}`,
        method: 'GET'
      })
      if (err) throw err
      if (res.statusCode === 200 && res.data) {
        const org = res.data
        form.name = org.name || form.name
        // 将组织类型映射为前端标签
        const typeLabel = mapOrgTypeToLabel(org.type)
        if (typeLabel) {
          form.companyType = typeLabel
          companyTypeIndex.value = companyTypeOptions.indexOf(typeLabel)
          identityTypeOptions.value = identityTypeMap[form.companyType]
        }
      } else {
        // 404等情况提示用户检查
        if (res.statusCode === 404) {
          uni.showToast({ title: '未找到该企业，请检查信用代码', icon: 'none' })
        }
      }
    } catch (e) {
      // 静默失败，不影响用户继续填写
      console.warn('fetchOrgByCreditCode error', e)
    }
  }

  function mapOrgTypeToLabel(typeVal) {
    // 后端org.type目前是字符串（如“学校/民营企业/国有企业/其他”或数字编码），这里做容错映射
    if (!typeVal) return null
    const v = String(typeVal)
    if (companyTypeOptions.includes(v)) return v
    if (v === '0' || /学校/.test(v)) return '学校'
    if (v === '1' || /民营/.test(v)) return '民营企业'
    if (v === '2' || /国有/.test(v)) return '国有企业'
    return '其他'
  }
  
  // 企业类型选择变化
  function onCompanyTypeChange(e) {
    companyTypeIndex.value = e.detail.value
    form.companyType = companyTypeOptions[companyTypeIndex.value]
    // 动态更新身份类型选项
    identityTypeOptions.value = identityTypeMap[form.companyType]
    identityTypeIndex.value = -1
    form.identityType = ''
  }
  // 身份类型选择变化
  function onIdentityTypeChange(e) {
    identityTypeIndex.value = e.detail.value
    form.identityType = identityTypeOptions.value[identityTypeIndex.value]
  }
  
  // 文件上传相关
  const fileUploadError = ref('')
  const fileUploadProgress = ref({}) // {uid: percent}
  const uploadedFiles = ref([]) // 已上传文件url
  const selectedFiles = ref([]) // 选择的临时文件列表（避免与 v-model 不同步）
  
  function onFileSelect(e) {
    // 选择文件时清空错误，并记录选择的临时文件
    fileUploadError.value = ''
    if (e && e.tempFiles) {
      selectedFiles.value = e.tempFiles.slice()
    }
  }
  function onFileProgress({ file, percent }) {
    fileUploadProgress.value[file.uid] = percent
  }
  function onFileSuccess({ file, tempFilePath, res }) {
    // 成功后可处理返回url
  }
  function onFileFail({ file, errMsg }) {
    fileUploadError.value = '文件上传失败: ' + errMsg
  }
  
  // 上传所选文件至后端，返回可访问的文件URL数组
  async function uploadFilesWx() {
    const token = uni.getStorageSync('accessToken')
    const uploadResults = []
    const filesToUpload = selectedFiles.value.length ? selectedFiles.value : form.files
    for (const file of filesToUpload) {
      const filePath = file.path || file.tempFilePath || file.url
      await new Promise((resolve, reject) => {
        uni.uploadFile({
          url: `${NETWORK_CONFIG.API_BASE_URL}/feedback/upload`,
          filePath,
          name: 'file',
          header: {
            'Authorization': 'Bearer ' + token
          },
          success: (res) => {
            try {
              const data = JSON.parse(res.data || '{}')
              if ((res.statusCode === 200 || data.code === 200) && data.url) {
                const normalizedUrl = data.url.startsWith('http://') ? data.url.replace('http://', 'https://') : data.url
                uploadResults.push(normalizedUrl)
                resolve()
              } else {
                fileUploadError.value = (data && (data.message || data.msg)) || '文件上传失败'
                reject(new Error('upload-failed'))
              }
            } catch (e) {
              fileUploadError.value = '文件上传返回异常'
              reject(e)
            }
          },
          fail: (err) => {
            fileUploadError.value = err && err.errMsg ? err.errMsg : '文件上传失败'
            reject(err)
          }
        })
      })
    }
    return uploadResults
  }
  
  // 表单提交
  const submitting = ref(false)
  async function onSubmit() {
    // 1. 校验表单
    if (creditCodeError.value) {
      uni.showToast({ title: creditCodeError.value, icon: 'none' })
      return
    }
    fileUploadError.value = ''
    const formRefVal = formRef.value
    let valid = false
    await formRefVal.validate().then(() => { valid = true }).catch(() => { valid = false })
    if (!valid) return
    if (!selectedFiles.value.length && !form.files.length) {
      fileUploadError.value = '请上传证明材料'
      return
    }
    submitting.value = true
    try {
      // 2. 上传文件
      const fileUrls = await uploadFilesWx()
      // 3. 提交表单
      const token = uni.getStorageSync('accessToken')
      const res = await uni.request({
        url: `${NETWORK_CONFIG.API_BASE_URL}/enterprise/verify`,
        method: 'POST',
        header: {
          'Authorization': 'Bearer ' + token,
          'Content-Type': 'application/json'
        },
        data: {
          companyName: form.name,
          creditCode: form.creditCode,
          companyType: form.companyType,
          identityType: form.identityType,
          files: fileUrls,
          description: form.desc
        }
      })
      if ((res.statusCode === 200 && res.data && res.data.code === 200) || (res.data && res.data.code === 200)) {
        uni.showToast({ title: '提交成功', icon: 'success' })
        setTimeout(() => {
          uni.redirectTo({ url: '/pages/company/status' })
        }, 800)
      } else {
        const errorMsg = (res && res.data && (res.data.message || res.data.msg)) || '提交失败'
        uni.showToast({ title: errorMsg, icon: 'none' })
      }
    } catch (e) {
      uni.showToast({ title: '提交失败', icon: 'none' })
    } finally {
      submitting.value = false
    }
  }
  
  // 返回按钮
  function onBack() {
    uni.navigateBack()
  }
  
  // 权限处理（如需获取用户信息、文件权限等）
  onLoad(() => {
    // 可在此处处理权限申请
  })
  onShow(() => {
    // 页面展示时刷新等
  })
  
  // 初始化身份类型选项
  watch(() => form.companyType, (val) => {
    identityTypeOptions.value = identityTypeMap[val] || []
    identityTypeIndex.value = -1
    form.identityType = ''
  })
  
  const formRef = ref(null)
  </script>
  
  <style scoped>
  .company-auth-bg {
    min-height: 100vh;
    background: #f6f8fa;
  }
  .company-auth-container {
    background: #fff;
    border-radius: 18px;
    margin: 24px 16px;
    padding: 24px 18px 18px 18px;
    box-shadow: 0 2px 12px #1ecfff22;
  }
  .picker-view {
    padding: 12px 0;
    color: #333;
  }
  .submit-btn {
    margin-top: 32px;
    width: 100%;
    background: linear-gradient(90deg, #1ecfff 0%, #357abd 100%);
    color: #fff;
    font-size: 1.1rem;
    font-weight: bold;
    border-radius: 8px;
    padding: 14px 0;
    box-shadow: 0 2px 8px #1ecfff33;
  }
  .error-msg {
    color: #e53e3e;
    font-size: 0.92rem;
    margin-top: 4px;
  }
  .desc-textarea {
    width: 100%;
    min-height: 100px;         /* 适配红框高度 */
    border-radius: 8px;
    border: 1.5px solid #e0e7ff;
    padding: 10px;
    font-size: 1rem;
    background: #f8f9ff;
    color: #333;
    box-sizing: border-box;
    resize: none;
  }
  </style>
  